﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using User.Identity.Authentication;
using User.Identity.Models;
using User.Identity.Services;

namespace User.Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
                .AddProfileService<ProfileService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var options = new ServiceDiscoveryOptions();
            Configuration.Bind("ServiceDiscovery", options);

            var serviceRegistration = new AgentServiceRegistration()
            {
                Address = options.Service.Address,
                Checks = new AgentServiceCheck[]{
                    new AgentServiceCheck() {
                     Interval=TimeSpan.FromSeconds(10),
                      Timeout=TimeSpan.FromSeconds(3),
                       DeregisterCriticalServiceAfter= TimeSpan.FromSeconds(3),
                        HTTP=$"{options.Service.GetUrl()}/api/healthcheck/ping",
                } },
                ID = $"{options.Service.Name}_{options.Service.Address}_{options.Service.Port}",
                Name = options.Service.Name,
                Port = options.Service.Port
            };
            lifetime.ApplicationStarted.Register(() =>
            {
                var consulClient = new ConsulClient();
                consulClient.Agent.ServiceRegister(serviceRegistration).ConfigureAwait(false);
            });
            lifetime.ApplicationStopped.Register(() =>
            {
                var consulClient = new ConsulClient();
                consulClient.Agent.ServiceDeregister(serviceRegistration.ID).ConfigureAwait(false);
            });
            app.UseMvc();
            app.UseIdentityServer();
        }
    }
}
